//
//  OAuthViewController.swift
//  WBDemo
//
//  Created by Meng on 17/2/8.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {

    @IBOutlet weak var webView: UIWebView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_key)&redirect_uri=\(WB_Redirect_uri)"
        
        guard let url = URL(string: urlStr) else {
            return
        }
        
        let request = URLRequest(url: url)
        
        webView.loadRequest(request)
        
    }
    // 关闭
    @IBAction func closeAction(_ sender: UIBarButtonItem) {
        dismiss(animated: true, completion: nil)
    }
    // MARK: - UIWebViewDelegate
    
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show(withStatus: "哥们使劲加载中...")
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
//        MYLog(request)
        
        guard let urlStr = request.url?.absoluteString else {
            return false
        }
        
        if !urlStr.hasPrefix(WB_Redirect_uri) {
            return true
        }
        let codeStr = "code="
        guard let queryStr = request.url?.query else {
            return false
        }
        if queryStr.hasPrefix(codeStr) {
            MYLog("授权成功")
            // http://www.jianshu.com/u/5b9cf22a3692?code=f8541166ae29c2aca9d4b0755d4dcf52
            // 取出code
            let code = queryStr.substring(from: codeStr.endIndex)
            loadAccessToken(codeStr: code)
            return true
        }
        MYLog("授权失败")
        // http://www.jianshu.com/u/5b9cf22a3692?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        return true
    }
    
    private func loadAccessToken(codeStr: String) {
        MYLog(codeStr)
        
        let path = "oauth2/access_token"
        
        let parameters = ["client_id": WB_App_key, "client_secret": WB_App_secret, "grant_type": "authorization_code", "code": codeStr, "redirect_uri": WB_Redirect_uri]
        
        NetworkTool.shareInstance.post(path, parameters: parameters, progress: nil, success: { (task: URLSessionDataTask, dictData: Any?) in
            MYLog(dictData)
            /*
             {
             "access_token" = "2.00zzCFJE0PVzyjb87b67df1b09tIsl";
             "expires_in" = 157679999;
             "remind_in" = 157679999;
             uid = 3798721523;
             }
             */
            let account = UserAccount.init(dict: dictData as! [String : AnyObject])
            account.loadUserInfo()
            NotificationCenter.default.post(name: NSNotification.Name.init(SwitchRootViewController), object: false)
        }) { (task: URLSessionDataTask?, error: Error) in
            MYLog(error)
        }
    }

}

/*
 新浪微博如何进行OAuth授权:
 1.成为新浪的开发者
 在: open.weibo.com上注册一个账号
 
 2.在开发者平台创建一个属于自己的应用程序
 App Key：679471221
 App Secret：1e7f50d69b367155f0340634d5752692
 
 3.对自己创建的应用程序, 开始进行OAuth授权
 3.1获取未授权的RequestToken(获取登录界面)
https://api.weibo.com/oauth2/authorize?client_id=679471221&redirect_uri=http://www.jianshu.com/u/5b9cf22a3692
 
 3.2获取已经授权的RequestToken(让用户登录)
 只要用户输入账号密码, 并且点击授权
http://www.jianshu.com/u/5b9cf22a3692?code=f8541166ae29c2aca9d4b0755d4dcf52
 其中code= 后面的字符串就是已经授权的RequestToken
 
 3.3利用已经授权的RequestToken换取AccessToken
 */
